from django.db import models
from django.urls import reverse
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill


# Create your models here.



class Category(models.Model):
    name = models.CharField(max_length=200, db_index=True, verbose_name='商品分类')
    slug = models.SlugField(max_length=200, db_index=True, verbose_name='商品分类简称')

    class Meta:
        ordering = ['name']
        verbose_name = verbose_name_plural = '商品分类管理'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('shop:product_list_by_category', args=[self.slug])


class Product(models.Model):
    category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE, verbose_name='所属分类')
    name = models.CharField(max_length=200, db_index=True, verbose_name='商品名称')
    slug = models.SlugField(max_length=200, db_index=True, verbose_name='商品简称')
    image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True, verbose_name='商品原图')
    image_30x30 = ImageSpecField(source='image',
                                 processors=[ResizeToFill(30, 30)],  # 处理后的图像大小
                                 format='JPEG',  # 处理后的图片格式
                                 options={'quality': 100})  # 处理后的图片质量
    desc = models.TextField(blank=True, verbose_name='商品描述')
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name='商品体格')
    available = models.BooleanField(default=True, verbose_name='状态')
    created = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated = models.DateTimeField(auto_now=True, verbose_name='修改时间')

    class Meta:
        ordering = ['name']
        index_together = (('id', 'slug'),)
        verbose_name_plural = verbose_name = '商品管理'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('shop:product_detail', args=[self.id, self.slug])
